﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
using System.Data.Services.Client;
using System.Diagnostics;

namespace PC.AzureMultiApp.Storage
{
    public class EventDataSource
    {
        StorageContext context;

        public EventDataSource()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                if (RoleEnvironment.IsAvailable)
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                else
                    configSetter(ConfigurationManager.AppSettings[configName]);
            });


            var sa = CloudStorageAccount.FromConfigurationSetting("azuremultiappstorage");

            this.context = new StorageContext(sa.TableEndpoint.ToString(), sa.Credentials);

            var ctc = sa.CreateCloudTableClient();

            ctc.CreateTableIfNotExist(GlobalDef.TableName);
        }

        public void Clear()
        {
            foreach (var item in this.context.AzureEvents)
                this.context.DeleteObject(item);
            this.context.SaveChanges();
        }

        public IEnumerable<AzureEventEntity> GetEvents()
        {
            var query = (from c in this.context.AzureEvents
                          select c).Take(200).AsTableServiceQuery<AzureEventEntity>();

            List<AzureEventEntity> azureEventEntitiesList = null;
            try
            {
                azureEventEntitiesList = query.Execute().ToList<AzureEventEntity>();
            }
            catch (DataServiceQueryException ex)
            {
                Trace.TraceError(ex.Message);

                // Swallow error from attempt to query WadPerformanceCountersTable before the Diagnostics Agent creates it.
            }

            return azureEventEntitiesList;
        }

       
    }
}
